/**
 * 微信小程序缓存函数
 */

const SEARCH_KEY = '__search__'
const SEARCH_MAX_LENGTH = 15

/**
 * 插入数组操作
 */
function insertArray (arr, val, compare, maxLen) {
  // 查找数组中是否包含插入信息并返回下标
  let index = arr.findIndex(compare)
  if (index === 0) {
    return
  }
  // 如果下标大于0，则移除该下标中的值，从数组头部插入该值
  if (index > 0) {
    arr.splice(index, 1)
  }
  arr.unshift(val)
  // 超出存储长度，移除最后一个项
  if (maxLen && arr.length > maxLen) {
    arr.pop()
  }
}

/**
 * 删除数组项
 */
function deleteFromArray (arr, compare) {
  let index = arr.findIndex(compare)
  if (index > -1) {
    arr.splice(index, 1)
  }
}

/**
 * 保存搜索记录
 */
export function saveSearch (query) {
  let searches = wx.getStorageSync(SEARCH_KEY) || []
  insertArray(searches, query, (item) => {
    return item === query
  }, SEARCH_MAX_LENGTH)
  wx.setStorageSync(SEARCH_KEY, searches)
  return searches
}

/**
 * 加载缓存中的记录
 */
export function loadSearch () {
  return wx.getStorageSync(SEARCH_KEY)
}

/**
 * 删除单个历史记录
 */
export function deleteSearch (query) {
  let searches = wx.getStorageSync(SEARCH_KEY)
  deleteFromArray(searches, (item) => {
    return item === query
  })
  wx.setStorageSync(SEARCH_KEY, searches)
  return searches
}

/**
 * 清空历史记录
 */
export function clearSearch () {
  wx.removeStorageSync(SEARCH_KEY)
  return []
}
